<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();

interface Message {
    id: number;
    type: 'user' | 'ai';
    content: string;
    timestamp: Date;
}

const messages = ref<Message[]>([
    {
        id: 1,
        type: 'ai',
        content: 'HI，我是专属智能客服，土豆炖蘑菇\n遇到问题，请尽管问我，我来帮你解答',
        timestamp: new Date()
    }
]);

const inputMessage = ref('');
const chatContainer = ref<HTMLElement>();
const isInputFocused = ref(false);

// 猜你想问的问题列表
const suggestedQuestions = ref([
    '如何绑定电子就诊卡？',
    '门诊挂号如何操作？',
    '处方能在手机上缴费吗？',
    '门诊挂号能使用医保支付吗？',
    '住院预交金能给亲友充值吗？',
    '如何在手机上进行门诊挂号退费？'
]);

// 猜你想做的功能
const suggestedActions = ref([
    { title: '门诊挂号', icon: 'calendar-o', action: 'appointment' },
    { title: '门诊缴费', icon: 'balance-o', action: 'payment' },
    { title: '门诊报告', icon: 'description', action: 'report' }
]);

// 医疗相关的预设回答
const medicalResponses = {
    '绑定': '电子就诊卡绑定流程：\n1. 打开APP，点击"个人中心"\n2. 选择"就诊卡管理"\n3. 点击"绑定就诊卡"\n4. 输入就诊卡号和密码\n5. 验证身份信息\n6. 绑定成功\n\n如有问题，请咨询客服热线：400-123-4567',
    '挂号': '门诊挂号操作步骤：\n1. 点击首页"预约挂号"\n2. 选择科室和医生\n3. 选择就诊时间\n4. 填写患者信息\n5. 确认预约信息\n6. 支付挂号费\n7. 预约成功\n\n支持医保支付，请确保已绑定医保卡',
    '缴费': '处方缴费方式：\n1. 手机APP缴费：\n   - 打开APP，点击"门诊缴费"\n   - 选择待缴费处方\n   - 确认费用后支付\n2. 自助机缴费：门诊大厅自助机\n3. 窗口缴费：收费处\n\n支持微信、支付宝、银行卡等多种支付方式',
    '医保': '医保支付说明：\n1. 门诊挂号：支持医保支付\n2. 处方缴费：支持医保统筹\n3. 住院费用：支持医保报销\n\n使用医保支付前，请确保：\n- 已绑定医保卡\n- 医保卡状态正常\n- 在医保定点医院就诊',
    '充值': '住院预交金充值：\n1. 可以为亲友充值：\n   - 输入患者身份证号\n   - 选择充值金额\n   - 确认支付\n2. 充值方式：\n   - 在线充值\n   - 自助机充值\n   - 窗口充值\n\n充值金额：100-10000元',
    '退费': '门诊挂号退费流程：\n1. 打开APP，点击"我的预约"\n2. 选择要退费的预约\n3. 点击"申请退费"\n4. 选择退费原因\n5. 确认退费\n6. 费用原路退回\n\n退费时间：1-3个工作日到账'
};

// 发送消息
const sendMessage = () => {
    if (!inputMessage.value.trim()) return;

    // 添加用户消息
    const userMessage: Message = {
        id: Date.now(),
        type: 'user',
        content: inputMessage.value,
        timestamp: new Date()
    };
    messages.value.push(userMessage);

    const userInput = inputMessage.value;
    inputMessage.value = '';

    // 模拟AI回复
    setTimeout(() => {
        const aiResponse = generateAIResponse(userInput);
        const aiMessage: Message = {
            id: Date.now() + 1,
            type: 'ai',
            content: aiResponse,
            timestamp: new Date()
        };
        messages.value.push(aiMessage);
        scrollToBottom();
    }, 1000);
};

// 生成AI回复
const generateAIResponse = (userInput: string): string => {
    const input = userInput.toLowerCase();

    // 检查是否包含关键词
    for (const [keyword, response] of Object.entries(medicalResponses)) {
        if (input.includes(keyword)) {
            return response;
        }
    }

    // 默认回复
    const defaultResponses = [
        '我理解您的问题，但可能需要更具体的信息。您可以询问关于绑定就诊卡、挂号、缴费、医保、充值、退费等方面的问题。',
        '抱歉，我没有完全理解您的问题。请尝试用更具体的词语描述，比如"绑定"、"挂号"、"缴费"等。',
        '您的问题很有价值，为了更好地帮助您，请告诉我您具体想了解什么？比如就诊流程、费用查询、操作指南等。',
        '我目前主要可以回答关于医疗服务的常见问题，如就诊卡绑定、挂号缴费、医保支付等。请告诉我您具体需要什么帮助？'
    ];

    return defaultResponses[Math.floor(Math.random() * defaultResponses.length)];
};

// 滚动到底部
const scrollToBottom = async () => {
    await nextTick();
    if (chatContainer.value) {
        chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    }
};

// 处理建议问题点击
const handleSuggestedQuestion = (question: string) => {
    inputMessage.value = question;
    sendMessage();
};

// 处理建议操作点击
const handleSuggestedAction = (action: string) => {
    switch (action) {
        case 'appointment':
            router.push('/patient-list');
            break;
        case 'payment':
            router.push('/self-payment');
            break;
        case 'report':
            // 跳转到报告查询页面
            break;
    }
};

// 换一批问题
const refreshQuestions = () => {
    const newQuestions = [
        '如何查询检查报告？',
        '住院费用如何查询？',
        '如何修改预约时间？',
        '医保卡丢失怎么办？',
        '如何申请病历复印？',
        '急诊就医流程是什么？'
    ];
    suggestedQuestions.value = newQuestions;
};

// 结束对话，跳转到问卷列表
const endChat = () => {
    router.push('/questionnaire-list');
};

// 处理输入框焦点
const handleInputFocus = () => {
    isInputFocused.value = true;
    setTimeout(() => {
        scrollToBottom();
    }, 300);
};

const handleInputBlur = () => {
    isInputFocused.value = false;
};

onMounted(() => {
    scrollToBottom();
});
</script>

<template>
    <div class="chat-page">
        <van-nav-bar title="智能客服" left-arrow @click-left="router.back()">
            <template #right>
                <van-icon name="ellipsis" />
                <van-icon name="eye-o" style="margin-left: 8px;" />
            </template>
        </van-nav-bar>

        <div class="chat-container" ref="chatContainer">
            <div class="messages">
                <!-- AI欢迎消息 -->
                <div class="message ai">
                    <div class="ai-avatar">
                        <van-icon name="robot-o" size="24" color="#007AFF" />
                    </div>
                    <div class="message-content">
                        <div class="message-text">{{ messages[0].content }}</div>
                    </div>
                </div>

                <!-- 猜你想问 -->
                <div class="suggested-section">
                    <div class="section-header">
                        <span class="section-title">猜你想问</span>
                        <van-button size="mini" type="primary" plain @click="refreshQuestions">
                            换一批
                        </van-button>
                    </div>
                    <div class="question-list">
                        <div v-for="(question, index) in suggestedQuestions" :key="index" class="question-item"
                            @click="handleSuggestedQuestion(question)">
                            {{ index + 1 }}. {{ question }}
                        </div>
                    </div>
                </div>

                <!-- 猜你想做 -->
                <div class="suggested-section">
                    <div class="section-header">
                        <span class="section-title">猜你想做</span>
                    </div>
                    <div class="action-grid">
                        <div v-for="action in suggestedActions" :key="action.title" class="action-item"
                            @click="handleSuggestedAction(action.action)">
                            <div class="action-icon">
                                <van-icon :name="action.icon" size="20" color="#007AFF" />
                            </div>
                            <div class="action-title">{{ action.title }}</div>
                        </div>
                    </div>
                </div>

                <!-- 其他消息 -->
                <div v-for="message in messages.slice(1)" :key="message.id" :class="['message', message.type]">
                    <div class="message-content">
                        <div class="message-text">{{ message.content }}</div>
                        <div class="message-time">
                            {{ message.timestamp.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }) }}
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 悬浮键盘输入区域 -->
        <div class="floating-keyboard" :class="{ 'focused': isInputFocused }">
            <div class="keyboard-container">
                <div class="input-wrapper">
                    <van-icon name="volume-o" class="voice-icon" />
                    <van-field v-model="inputMessage" placeholder="请简述您的问题" @keyup.enter="sendMessage"
                        @focus="handleInputFocus" @blur="handleInputBlur" class="message-input" />
                    <van-button type="primary" size="small" @click="sendMessage" :disabled="!inputMessage.trim()"
                        class="send-btn">
                        发送
                    </van-button>
                </div>
            </div>
        </div>

        <!-- 结束按钮 -->
        <div class="end-button-container">
            <van-button type="default" size="large" @click="endChat" class="end-btn">
                结束对话
            </van-button>
        </div>
    </div>
</template>

<style scoped>
.chat-page {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background: #f5f5f5;
}

.chat-container {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    background: #f5f5f5;
    padding-bottom: 120px;
    /* 为悬浮键盘留出空间 */
}

.messages {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.message {
    display: flex;
    margin-bottom: 8px;
}

.message.user {
    justify-content: flex-end;
}

.message.ai {
    justify-content: flex-start;
    align-items: flex-start;
}

.ai-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #f0f8ff;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 8px;
    flex-shrink: 0;
}

.message-content {
    max-width: 70%;
    padding: 12px 16px;
    border-radius: 18px;
    position: relative;
}

.message.user .message-content {
    background: #007AFF;
    color: white;
    border-bottom-right-radius: 4px;
}

.message.ai .message-content {
    background: white;
    color: #333;
    border: 1px solid #e0e0e0;
    border-bottom-left-radius: 4px;
}

.message-text {
    font-size: 14px;
    line-height: 1.4;
    white-space: pre-line;
}

.message-time {
    font-size: 11px;
    opacity: 0.7;
    margin-top: 4px;
    text-align: right;
}

.suggested-section {
    background: white;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.section-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.question-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.question-item {
    padding: 8px 12px;
    background: #f8f9fa;
    border-radius: 8px;
    font-size: 14px;
    color: #333;
    cursor: pointer;
    transition: background-color 0.2s;
}

.question-item:hover {
    background: #e9ecef;
}

.action-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
}

.action-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 16px 8px;
    background: #f8f9fa;
    border-radius: 12px;
    cursor: pointer;
    transition: background-color 0.2s;
}

.action-item:hover {
    background: #e9ecef;
}

.action-icon {
    margin-bottom: 8px;
}

.action-title {
    font-size: 12px;
    color: #333;
    text-align: center;
}

/* 悬浮键盘样式 */
.floating-keyboard {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: white;
    border-top: 1px solid #e0e0e0;
    padding: 12px 16px;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    z-index: 1000;
}

.floating-keyboard.focused {
    box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.15);
}

.keyboard-container {
    max-width: 600px;
    margin: 0 auto;
}

.input-wrapper {
    display: flex;
    align-items: center;
    gap: 8px;
    background: #f8f9fa;
    border-radius: 24px;
    padding: 8px 16px;
    transition: all 0.3s ease;
}

.floating-keyboard.focused .input-wrapper {
    background: white;
    box-shadow: 0 2px 8px rgba(0, 122, 255, 0.1);
    border: 1px solid #007AFF;
}

.voice-icon {
    color: #666;
    font-size: 20px;
}

.message-input {
    flex: 1;
    background: transparent;
    border: none;
    padding: 0;
}

.send-btn {
    height: 36px;
    padding: 0 16px;
    border-radius: 18px;
}

.end-button-container {
    padding: 16px;
    background: white;
    border-top: 1px solid #e0e0e0;
    margin-top: 80px;
    /* 为悬浮键盘留出空间 */
}

.end-btn {
    width: 100%;
    height: 44px;
    border-radius: 22px;
    font-size: 16px;
    color: #666;
    background: #f8f9fa;
    border: 1px solid #e0e0e0;
}

:deep(.van-field__control) {
    font-size: 14px;
}

:deep(.van-button--small) {
    height: 32px;
    padding: 0 16px;
}
</style>